<template>
  <el-container>
    <el-aside width="200px">
      <el-scrollbar height="calc(100vh - 175px);">
        <el-tree
          style="max-width: 600px"
          :props="orgTreeProps"
          :load="loadNode"
          node-key="id"
          :default-expanded-keys="expandedKeys"
          :expand-on-click-node="false"
          lazy
          @node-click="clickTreeNode"
        >
          <template #default="{ node }">
            <template v-if="node.data.typeIcon">
              <Icon
                :icon="node.data.typeIcon"
                :color="node.data.typeColor"
                :hoverColor="node.data.typeColor"
              />
            </template>
            <template v-else>
              <Icon icon="octicon:organization" color="#008000" hoverColor="#008000" />
            </template>
            <span class="ml-1">{{ node.label }}</span>
          </template>
        </el-tree>
      </el-scrollbar>
    </el-aside>
    <WsmTable ref="table" v-model="queryFormType" load-url="/rbac-server/rbac/orgrole/page">
      <template #title>{{ title }}</template>
      <template #button="{ row }">
        <el-button
          type="primary"
          v-hasPermi="'add'"
          @click="addForm.show()"
          v-if="initData.orgId != 'root'"
          >{{ t('rbac.orgRole.add') }}</el-button
        >
        <template v-if="row">
          <el-button v-hasPermi="'delete'" @click="remove(row.id)" type="danger">{{
            t('common.remove')
          }}</el-button>
          <el-button v-hasPermi="'authList'" @click="authList(row.id)" type="warning">{{
            t('rbac.orgRole.authList')
          }}</el-button>
        </template>
      </template>
      <template #column>
        <el-table-column prop="userNum" :label="t('rbac.orgRole.userNum')" width="120" />
        <el-table-column prop="orgName" :label="t('rbac.orgRole.orgName')" width="220" />
        <el-table-column prop="typeName" :label="t('rbac.orgRole.typeName')" width="220" />
        <el-table-column prop="note" :label="t('rbac.orgRole.note')" />
      </template>
    </WsmTable>
  </el-container>

  <WsmForm
    ref="addForm"
    v-model="addData"
    submit-url="/rbac-server/rbac/orgrole/adds"
    label-position="top"
    :init-data="initData"
    :title="t('rbac.orgRole.add')"
    @success="flushed"
  >
    <template #default="{ form }">
      <el-form-item prop="code" :label="t('rbac.orgRole.typeName')">
        <el-checkbox-group v-model="form.code">
          <el-checkbox
            v-for="item in roleTypes"
            :key="item.code"
            :label="item.typeName"
            :value="item.code"
          >
            {{ item.typeName }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </template>
  </WsmForm>
  <AuthUser ref="authUser" @after-delete="afterDelete" />
</template>
<script setup lang="ts">
import { WsmTable } from '@/components/WsmTable'
import { WsmForm } from '@/components/WsmForm'
import { QueryFormType } from '@/components/WsmTable/src/types'
import { computed, reactive, ref } from 'vue'
import { useI18n } from '@/hooks/web/useI18n'
import { FormDataType } from '@/components/WsmForm/src/types'
import { getTreeChildApi } from '@/api/rbac/org'
import { delApi } from '@/api/rbac/orgrole'
import type Node from 'element-plus/es/components/tree/src/model/node'
import { useUserStore } from '@/store/modules/user'
import { OrgTreeDataType } from '../Org/types'
import { listRoleTypeApi } from '@/api/rbac/roletype'
import { RoleTypeType } from '@/api/rbac/roletype/types'
import { ElMessageBox } from 'element-plus'
import AuthUser from './components/AuthUser.vue'

const { t } = useI18n()

const userStore = useUserStore()
//列表标题
const orgName = ref(t('rbac.org.orgRoot'))

//新增表单对象
const addForm = ref()
const initData = ref({
  code: [],
  orgId: 'root'
})
const addData: FormDataType = reactive({
  code: [],
  orgId: 'root'
})

//表格对象
const table = ref()

//树配置项
const orgTreeProps = {
  label: 'orgName',
  isLeaf: 'isLeaf'
}
var treeData: OrgTreeDataType[] = [
  {
    id: 'root',
    parentId: '',
    orgName: t('rbac.org.orgRoot'),
    isLeaf: false
  }
]

const queryFormType: QueryFormType = {
  orgId: {
    value: 'root',
    clear: false
  }
}

const initParams = (data: OrgTreeDataType) => {
  queryFormType.orgId.value = data.id
  orgName.value = data.orgName
  initData.value.orgId = data.id
  loadRoleTypes(data.id)
}

const expandedKeys = ref(['root'])
//树的点击事件
const clickTreeNode = (data: OrgTreeDataType) => {
  initParams(data)
  flushed()
}

const title = computed(() => {
  return orgName.value + '(' + queryFormType.orgId.value + ')'
})

//加载树代码
const loadNode = async (
  node: Node,
  resolve: (data: OrgTreeDataType[]) => void,
  reject: () => void
) => {
  if (node.level == 0) {
    const userTypeId = userStore.getUserInfo?.userType.id
    if (userTypeId == 'administrator') {
      initParams(treeData[0])
      return resolve(treeData)
    } else {
      const queryOrg = userStore.getUserInfo?.queryOrg as OrgTreeDataType
      expandedKeys.value = [queryOrg.id]
      initParams(queryOrg)
      queryOrg.isLeaf = false
      queryOrg.isParent = true
      return resolve([queryOrg])
    }
  }
  const rs = await getTreeChildApi({ parentId: node.data.id })
  if (rs.success) {
    return resolve(rs.data)
  } else {
    return reject()
  }
}

const roleTypes = ref<RoleTypeType[]>([])

//加载可以配置的资源
const loadRoleTypes = async (orgId: string) => {
  const rs = await listRoleTypeApi(orgId)
  if (rs.success) {
    roleTypes.value = rs.data
  }
}

const remove = async (id: string) => {
  ElMessageBox.confirm(t('common.removeMessage'), t('common.delWarning'), {
    confirmButtonText: t('common.ok'),
    cancelButtonText: t('common.cancel'),
    type: 'warning'
  }).then(async () => {
    const rs = await delApi({ id })
    if (rs.success) {
      table.value.load(1)
    }
  })
}

const authUser = ref()

const authList = (id: string) => {
  authUser.value.show(id)
}

const afterDelete = () => {
  table.value.load()
}

const flushed = () => {
  table.value.load(1)
}
</script>

<style scoped></style>
